<template>
    <a-form ref="homeBasedRef" :model="otherData" :rules="homebasedRules" layout="vertical">
        <a-row :gutter="24">
            <a-col :span="item.input_type == 'json' ? 24 : 12" v-for="(item, index) in homeBasedForm" :key="index">
                <a-form-item :label="item.input_name_cus" v-if="item.input_type == 'json'">
                    <a-table :columns="item.columns" :data-source="tableObj[item.field_name]" :rowKey="(r, i) => i"
                        :pagination="false">
                        <template v-for="col in item.columns.filter(
                            (item) => item?.key !== 'action'
                        )" #[col.title_key]="{ record, index }" :key="col.title_key">
                            {{ record }}{{ col.title_key }}{{ index }}
                        </template>

                        <template v-for="col in item.columns.filter(
                            (item) => item?.key !== 'action'
                        )" #[col.key]="{ record, index }" :key="col.key">
                            <div>
                                <template v-if="col.type == 'text'">
                                    <a-input v-model:value="tableObj[item.field_name][index][col.key]" placeholder="请输入"
                                        :maxlength="20" />
                                </template>

                                <template v-if="col.type === 'image'">
                                    <a-upload :action="$utils.imgAction" :headers="{ 'org-token': $store.getters.token }"
                                        accept="image/jpg,image/jpeg,image/gif,image/png" class="certificate-upload"
                                        list-type="picture-card"
                                        v-model:file-list="tableObj[item.field_name][index][col.key]"
                                        @preview="(file) => { handleHomeBasedPreview(file); }" @change="(info) => { handleHomeBasedUploadChange(info, item, index, col.key); }
                                            " name="image" :data="{ dir: 'org_personal' }">
                                        <div v-if="(record?.cert_list?.length || 0) < 3">
                                            <PlusOutlined />
                                            <div class="ant-upload-text">上传</div>
                                        </div>
                                    </a-upload>
                                    <a-modal :visible="previewVisible" :footer="null" @cancel="() => {
                                        previewVisible = false;
                                    }
                                        ">
                                        <img alt="example" style="width: 100%" :src="previewImage" />
                                    </a-modal>
                                </template>
                            </div>
                        </template>
                        <template #action="{ index }">
                            <MinusCircleOutlined :style="{
                                color: '#f81d22',
                                fontSize: '22px',
                                marginBottom: '20px',
                            }" @click="deleteHomeBasedTable(item, index)" />
                        </template>
                    </a-table>
                </a-form-item>
                <div v-if="item.input_type == 'json'" style="width: 100%; margin-bottom: 20px;" class="add-table"
                    @click="addHomeBasedTable(item)">
                    <PlusOutlined />
                    添加
                </div>
                <a-form-item v-if="item.input_type != 'json'" :label="item.input_name_cus" :name="item.field_name">
                    <div v-if="item.input_type == 'text'">
                        <a-input v-model:value="otherData[item.field_name]" :placeholder="'请输入' + item.input_name_cus" />
                    </div>
                    <div v-if="item.input_type == 'number'">
                        <a-input-number style="width: 100%;" :min="0" v-model:value="otherData[item.field_name]"
                            :placeholder="'请输入' + item.input_name_cus" />
                    </div>
                    <div v-if="item.input_type == 'select'">
                        <a-select v-model:value="otherData[item.field_name]" :placeholder="'请选择' + item.input_name_cus">
                            <a-select-option v-for="(item, index) in item.default_field_value" :value="item.id*1"
                                :key="item.id">{{ item.value }}</a-select-option>
                        </a-select>
                    </div>
                    <div v-if="item.input_type == 'multi_select'">
                        <a-select mode="multiple" allowClear v-model:value="otherData[item.field_name]"
                            :placeholder="'请选择' + item.input_name_cus">
                            <a-select-option v-for="(item, index) in item.default_field_value" :value="item.id"
                                :key="item.id">{{ item.value }}</a-select-option>
                        </a-select>
                    </div>
                    <div v-if="item.input_type == 'date'">
                        <a-date-picker @change="(date, dateString) => handleDateChange(date, dateString, item)"
                            style="width: 100%;" v-model:value="otherData[item.field_name + '_moment']" />
                    </div>
                </a-form-item>
            </a-col>
        </a-row>
        <div class="drawer-footer">
            <a-button class="mr-10" @click.prevent="btnClose">上一步</a-button>
            <a-button :loading="editLoading" type="primary" @click.prevent="btnOk"
            >保存</a-button
            >
        </div>
    </a-form>
</template>
<script>
import { message } from "ant-design-vue";
import {
    defineComponent,
    nextTick,
    reactive,
    ref,
    toRefs,
} from "vue";
import request from "../../../../common/utils/request";
import {
    PlusOutlined,
    MinusCircleOutlined,
} from "@ant-design/icons-vue";
import store from "../../../../store";
import moment from 'moment';
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

export default defineComponent({
    props: {
        id: {
            type: [Number, String],
            default: 0
        },
        params: {
            type: Object, 
            default: ()=>{return {}}
        }
    },

    components: {
        PlusOutlined,
        MinusCircleOutlined
    },
    setup(props, context) {
        // 拓展信息表单校验
        const homeBasedRef = ref()
        const state = reactive({
            homebasedRules: {},
            homeBasedForm: [],
            otherData: {},
            tableObj: {},
            previewImage: '',
            previewVisible: false,
            editLoading: false,
        })

        //扩展信息选择列表
        const getExtendList = () => {
            let village_type = store.getters.orgInfo.village_type
            request.get('/village', '/org/user/extend/list', {
                village_type,
                villageId: store.getters.buildingInfo.permissionBuildings[0].id
            }).then(res => {
                if (res.formField && res.formField.length > 0) {
                    state.homeBasedForm = res.formField
                    if(props.id){
                        getOtherInfo()
                    }
                    state.homeBasedForm.map(v => {
                        if (v.default_input_value) {
                            state.otherData[v.field_name] = v.default_input_value
                        } else if (v.input_type == 'select') {
                            state.otherData[v.field_name] = null
                        } else if (v.input_type == 'text') {
                            state.otherData[v.field_name] = ''
                        } else if (v.input_type == 'number') {
                            state.otherData[v.field_name] = null
                        } else if (v.input_type == 'multi_select') {
                            state.otherData[v.field_name] = []
                        } else if (v.input_type == 'json') {
                            let columns = []
                            v.json_fields.map(item => {
                                columns.push({
                                    title: item.input_name,
                                    dataIndex: item.field_name,
                                    key: item.field_name,
                                    title_key: item.field_name+'_title',
                                    type: item.input_type,
                                    resuired: item.is_required?true:false,
                                    slots: {
                                        title: item.field_name+'_title',
                                        customRender: item.field_name,
                                    },
                                })
                            })
                            columns.push({
                                title: "操作",
                                key: "action",
                                fixed: "right",
                                width: 80,
                                slots: {
                                    customRender: "action",
                                },
                            })
                            v.columns = columns
                            state.tableObj[v.field_name] = []
                        }
                        if (v.input_type == 'date') {
                            state.otherData[v.field_name] = ''
                            state.otherData[v.field_name + '_moment'] = null
                        }
                        if (v.is_required) {
                            if(v.input_type == 'text' || v.input_type == 'number'){
                                state.homebasedRules[v.field_name] = [{ required: true, message: '必填'}]
                            } else {
                                state.homebasedRules[v.field_name] = [{ required: true, message: '必填'}]
                            }
                        } else {
                            state.homebasedRules[v.field_name] = [{ required: false, message: '非必填' }]
                        }
                    })
                }
            })
        }

        //扩展信息唯一标识
        const getUniqueId = () => {
            request.get('/village', '/org/user/uniqueid').then(res => {
                state.otherData.unique_id = res.result
            })
        }

        //获取扩展信息详情
        const getOtherInfo = () => {
            let params = {}
            Object.assign(params, props.params)
            params.village_user_id = props.id
            params.village_id = store.getters.buildingInfo.permissionBuildings[0].id
            request.get('/village', '/org/user/extend/info', params).then(res => {
                if (res.result) {
                    Object.assign(state.otherData, res.result)
                    state.homeBasedForm.map(v=>{
                        if(v.input_type == 'json' && res.result[v.field_name]){
                            state.tableObj[v.field_name] = res.result[v.field_name]
                        }
                        if(v.input_type == 'date' && res.result[v.field_name]){
                            state.otherData[v.field_name + '_moment'] = moment(res.result[v.field_name])
                        }
                        if(v.input_type == 'select' && !res.result[v.field_name]){
                            state.otherData[v.field_name] = null
                        }
                        if(v.input_type == 'date' && !res.result[v.field_name]){
                            state.otherData[v.field_name] = null
                        }
                        if(v.input_type == 'multi_select' && !res.result[v.field_name]){
                            state.otherData[v.field_name] = []
                        }
                    })
                }
            })
        }

        // 拓展信息
        const deleteHomeBasedTable = (item, index) => {
            state.tableObj[item.field_name].splice(index, 1)
        }

        const addHomeBasedTable = (item) => {
            let Obj = {}
            item.json_fields.map(v => {
                if (v.input_type == 'image') {
                    Obj[v.field_name] = []
                } else {
                    Obj[v.field_name] = ''
                }
            })
            state.tableObj[item.field_name].push(Obj)
        }

        const handleHomeBasedPreview = async (file) => {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }

            state.previewImage = file.url || file.preview;
            state.previewVisible = true;
        }

        const handleHomeBasedUploadChange = (info, item, index, key) => {
            let resFileList = [...info.fileList];
            if (resFileList.length) {
                resFileList = resFileList.map((file) => {
                    if (file.response) {
                        if (file.response.code == 1000) {
                            file.url = file.response.data.fileUrl;
                        } else {
                            message.warning(file.response.msg);
                        }
                    }
                    return file;
                });
            }
            state.tableObj[item.field_name][index][key] = resFileList
        }

        const handleDateChange = (date, dateString, item) => {
            state.otherData[item.field_name] = dateString
            state.otherData[item.field_name + '_moment'] = date
        }
        
        const clearForm = () => {
            state.otherData = {}
        }

        const btnClose = () => {
            context.emit('closeExtend')
        }

        const btnOk = () => {
            homeBasedRef.value.validate().then(() => {
                state.homeBasedForm.filter(v=>v.input_type == 'json').map(v=>{
                    if(state.tableObj[v.field_name]){
                        state.otherData[v.field_name] = state.tableObj[v.field_name]
                    }
                })
                state.otherData.village_id = store.getters.buildingInfo.permissionBuildings[0].id
                let requestUrl = '/org/user/extend/info/add'
                if(state.otherData.id){
                    requestUrl = '/org/user/extend/info/update'
                }
                state.editLoading = true;
				let params = {}
				Object.assign(params, props.params)
				Object.assign(params, state.otherData)
				params.village_id = store.getters.buildingInfo.permissionBuildings[0].id
				params.village_user_id = props.id
				if(state.otherData.id){
					request.put("/village", requestUrl, params).then((res) => {
					    message.success(res.msg || "保存成功");
					    state.editLoading = false;
					    context.emit("success");
					    homeBasedRef.value.resetFields();
					}).catch(() => {
					    state.editLoading = false;
					})
				} else {
					request.post("/village", requestUrl, params).then((res) => {
					    message.success(res.msg || "添加成功");
					    state.editLoading = false;
					    context.emit("success");
					    homeBasedRef.value.resetFields();
					}).catch(() => {
					    state.editLoading = false;
					})
				}
            }).catch(err=>{
                const errorList = document.querySelectorAll(".ant-form-item-has-error");
				errorList[0]?.scrollIntoView({
					block: "center",
					behavior: "smooth",
				});
            })
        }

        getExtendList()
        getUniqueId()

        // if(count<2 || !state.otherData.unique_id) return
        // //如果没有更新拓展信息 则不调用保添加接口
        // request.post("/village", otherUrl, otherParams).then((res) => {});

        return {
            homeBasedRef,
            moment,
            ...toRefs(state),
            getExtendList,
            getUniqueId,
            getOtherInfo,
            //扩展信息操作
            clearForm,
            deleteHomeBasedTable,
            addHomeBasedTable,
            handleHomeBasedPreview,
            handleHomeBasedUploadChange,
            handleDateChange,
            btnClose,
            btnOk
        }
    }
})
</script>

<style scoped lang="less">
    .add-table {
        width: 100%;
        height: 36px;
        border: 1px dashed #eaeaea;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    }
</style>